package com.wmh.baseservice.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wmh generator
 * @since 2022-01-04
 */
@Api(tags = "商家端-区域相关接口")
@RestController
@RequestMapping(value = "merchant/merchantPlotRegion", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
@RequiresPermissions(logical = Logical.OR, value = {"土地管理操作", "所有权限"})
public class MerchantPlotRegionController {

    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantVegetablePlotService merchantVegetablePlotService;
    @Resource
    private MerchantPlotRentService merchantPlotRentService;
    @Resource
    private MerchantVegetableService merchantVegetableService;
    @Resource
    private MerchantPlotRentalMenuService merchantPlotRentalMenuService;


    @ApiOperation("区域列表")
    @PostMapping("regionList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String regionList(PageInfo pageInfo, Long plotId, String plotName, String name) {
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            id = parentMerchantInfo.getId();
        }
        Map<String, Object> map = new HashMap<>(16);
        PageResult<MerchantPlotRegion> pageResult = new PageResult<>();
        if (CommUtil.checkNull(id)) {
            map.put("merchantId", id);
        }
        if (CommUtil.checkNull(plotId)) {
            map.put("plotId", plotId);
        }
        if (CommUtil.checkNull(plotName)) {
            map.put("plotName", plotName);
        }
        if (CommUtil.checkNull(name)) {
            map.put("name", name);
        }
        Page<Object> vegetablePage = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        IPage<MerchantPlotRegion> merchantPlotRegionIPage = merchantPlotRegionService.getList(vegetablePage, map);
        pageResult.setPageSize(merchantPlotRegionIPage.getSize()).setPageNo(merchantPlotRegionIPage.getCurrent()).setPages(merchantPlotRegionIPage.getPages()).
                setTotal(merchantPlotRegionIPage.getTotal());
        pageResult.setList(merchantPlotRegionIPage.getRecords());
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("区域列表（无分页）")
    @PostMapping("regionListNoPage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String regionList() {
        Long merchantId = (Long) request.getAttribute("id");
        List<MerchantPlotRegion> merchantPlotRegions = merchantPlotRegionService.listForUpdate(new QueryWrapper<MerchantPlotRegion>().eq(MerchantPlotRegion.MERCHANT_ID, merchantId));
        return ReturnBody.success(merchantPlotRegions);
    }

    @ApiOperation("添加或修改")
    @PostMapping("addOrUpdate")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String addOrUpdate(Long id, Double lon, Double wide, String name, String remark) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            merchantId = parentMerchantInfo.getId();
        }
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getOneForUpdate(new QueryWrapper<MerchantVegetablePlot>().eq(MerchantVegetablePlot.RAW_MERCHANT_ID, merchantId));
        if (!CommUtil.checkNull(merchantVegetablePlot)) {
            return ReturnBody.error("无权操作，因为您未拥有土地");
        }
        if (CommUtil.checkNull(id)) {
            MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
            if (!CommUtil.checkNull(merchantPlotRegion)) {
                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
            }
            if (!merchantPlotRegion.getMerchantId().equals(merchantVegetablePlot.getRawMerchantId())) {
                return ReturnBody.error("无权操作，因为您不是该区域所属土地原商家");
            }
            if (merchantPlotRegion.getStatus() != 0) {
                return ReturnBody.error("出租中或已租出的不可做修改操作");
            }
            merchantPlotRegion.setWide(wide).setLon(lon).setName(name).setRemark(remark);
            if (!merchantPlotRegionService.updateById(merchantPlotRegion)) {
                return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
            }
        } else {
            //只有拥有该土地的才可以进行添加或修改
            MerchantPlotRegion merchantPlotRegion = new MerchantPlotRegion().setWide(wide).setLon(lon).setName(name).setRemark(remark).setPlotId(merchantVegetablePlot.getId()).setMerchantId(merchantId);
            if (!merchantPlotRegionService.save(merchantPlotRegion)) {
                return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
            }
        }
        return ReturnBody.success();
    }

    @ApiOperation("删除")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String delete(Long id) {
        //该区域非出租 无出租 且区域无产品
        Long merchantId = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(merchantId);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentMerchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            merchantId = parentMerchantInfo.getId();
        }
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        //只有拥有该土地的才可以进行添加或修改
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getOneForUpdate(new QueryWrapper<MerchantVegetablePlot>().eq(MerchantVegetablePlot.RAW_MERCHANT_ID, merchantId));
        if (!CommUtil.checkNull(merchantVegetablePlot)) {
            return ReturnBody.error("无权操作，因为您未拥有土地");
        }
        if (!merchantPlotRegion.getMerchantId().equals(merchantVegetablePlot.getRawMerchantId())) {
            return ReturnBody.error("无权操作，因为您不是该区域所属土地原商家");
        }
        if (merchantPlotRegion.getStatus() != 0) {
            return ReturnBody.error("该区域出租中，不可删除");
        }
        List<MerchantPlotRent> merchantPlotRents = merchantPlotRentService.listForUpdate(new QueryWrapper<MerchantPlotRent>().eq(MerchantPlotRent.STATUS, 1).eq(MerchantPlotRent.REGION_ID, id));
        if (merchantPlotRents.size() != 0) {
            return ReturnBody.error("该区域出租中，不可删除");
        }
        List<MerchantVegetable> merchantVegetables = merchantVegetableService.listForUpdate(new QueryWrapper<MerchantVegetable>().eq(MerchantVegetable.REGION_ID, id));
        if (merchantVegetables.size() != 0) {
            return ReturnBody.error("该区域有可以采摘或种植的产品，不可删除");
        }
        List<MerchantPlotRentalMenu> merchantPlotRentalMenus = merchantPlotRentalMenuService.listForUpdate(new QueryWrapper<MerchantPlotRentalMenu>().eq(MerchantPlotRentalMenu.REGION_ID, id));
        if (merchantPlotRentalMenus.size() != 0) {
            return ReturnBody.error("该区域设置了租赁套餐，请先将套餐删除后再删除该区域");
        }
        if (!merchantPlotRegionService.removeById(merchantPlotRegion.getId())) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("修改状态")
    @PostMapping("updateStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateStatus(Long id) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantPlotRegion merchantPlotRegion = merchantPlotRegionService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        //初始区域不可出租
        if (merchantPlotRegion.getType() == 1) {
            return ReturnBody.error("土地初始区域不可出租，请添加其他区域后再出租");
        }
        //只有拥有该土地的才可以进行添加或修改
        MerchantVegetablePlot merchantVegetablePlot = merchantVegetablePlotService.getOneForUpdate(new QueryWrapper<MerchantVegetablePlot>().eq(MerchantVegetablePlot.RAW_MERCHANT_ID, merchantId));
        if (!CommUtil.checkNull(merchantVegetablePlot)) {
            return ReturnBody.error("无权操作，因为您未拥有土地");
        }
        if (!merchantPlotRegion.getMerchantId().equals(merchantVegetablePlot.getRawMerchantId())) {
            return ReturnBody.error("无权操作，因为您不是该区域所属土地原商家");
        }
        //押金未填写，不可出租
        if (CommUtil.checkNull(merchantVegetablePlot)) {
            if (!CommUtil.checkNull(merchantVegetablePlot.getDeposit())) {
                return ReturnBody.error("请先查看该区域所属土地，完善土地押金后再出租");
            }
        }
        if (merchantPlotRegion.getStatus() == 1) {
            List<MerchantPlotRent> merchantPlotRents = merchantPlotRentService.listForUpdate(new QueryWrapper<MerchantPlotRent>().eq(MerchantPlotRent.STATUS, 1).eq(MerchantPlotRent.REGION_ID, id));
            if (merchantPlotRents.size() != 0) {
                return ReturnBody.error("该区域出租中，不可取消");
            }
        }
        if (merchantPlotRegion.getStatus() == 0) {
            //查套餐
            int count = merchantPlotRentalMenuService.count(new QueryWrapper<MerchantPlotRentalMenu>().eq(MerchantPlotRentalMenu.REGION_ID, id));
            if (count == 0) {
                return ReturnBody.error("请先到租赁管理-套餐管理中给当前区域添加租赁套餐后再出租该区域");
            }
        }
        merchantPlotRegion.setStatus(merchantPlotRegion.getStatus() == 0 ? 1 : 0);
        if (!merchantPlotRegionService.updateById(merchantPlotRegion)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

}
